<template>
	<view class="feedback-container">
		<view class="feedback-header">
			<text class="header-title">反馈中心</text>
		</view>

		<!-- 反馈类型选择 -->
		<view class="feedback-section">
			<text class="section-title">反馈类型</text>
			<radio-group class="type-radio-group">
				<label class="radio-label" v-for="item in feedbackTypes" :key="item.dictValue"
					@click="handleTypeChange(item.dictValue)">
					<radio :value="item.dictValue" :checked="currentType === item.dictValue" color="#007AFF" />
					<text>{{item.dictLabel}}</text>
				</label>
			</radio-group>
		</view>

		<!-- 反馈内容输入 -->
		<view class="feedback-section">
			<text class="section-title">反馈内容</text>
			<textarea v-model="feedbackContent" placeholder="请详细描述您的问题或建议..." class="content-textarea" maxlength="500"
				auto-height />
			<text class="text-count">{{feedbackContent.length}}/500</text>
		</view>

		<!-- 图片上传 -->
		<view class="feedback-section">
			<view class="feedback-section">
				<text class="section-title">相关截图（可选）</text>
			</view>
			<view class="demo">
				<block v-if="imageSrc">
					<!-- 如果纯在图片 -->
					<image :src="imageSrc" class="image" mode="widthFix"></image>
				</block>
				<block v-else>
					<!-- 没有原始图片 -->
					<view class="uni-hello-addfile" @click="chooseImage">+ 选择图片</view>
				</block>
			</view>
		</view>

		<!-- 联系方式 -->
		<view class="feedback-section">
			<text class="section-title">联系方式（选填）</text>
			<input v-model="contactInfo" placeholder="请留下您的手机号或邮箱" class="contact-input" />
		</view>

		<!-- 提交按钮 -->
		<button type="primary" class="submit-btn" :disabled="!canSubmit" @click="submitFeedback">
			提交反馈
		</button>
	</view>
</template>

<script>
	import {
		getDicts
	} from '@/api/system/dict/data.js'
	import {
		addUserFeedBack
	} from '@/api/system/feedback.js'
	import {
		getToken
	} from '@/utils/auth'

	export default {
		// name: 'feedback-center',
		data() {
			return {
				feedbackTypes: [],
				currentType: '',
				feedbackContent: '',
				maxImageCount: 3,
				contactInfo: '',
				isSubmitting: false,
				title: "请求下载图片",
				imageSrc: ''
			}
		},
		onLoad() {
			const feedback = "t_feedback_type"
			this.getDictsFeedback(feedback)
		},
		computed: {
			canSubmit() {
				return this.feedbackContent.trim().length > 0 && !this.isSubmitting
			}
		},
		methods: {

			//获取字典反馈类型状态
			getDictsFeedback(feedback) {
				getDicts(feedback).then(res => {
					console.log('反馈：', res);
					this.feedbackTypes = res.data
				})
			},
			handleTypeChange(e) {
				console.log('反馈值s：', e);
				this.currentType = e
			},
			chooseImage: function() {
				uni.chooseImage({
					count: 1, //最多可以选择的图片张数，默认9
					sizeType: ['compressed'], //original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					success: (res) => { //成功返回的函数
						console.log('图片路径为：', res.tempFilePaths[0]) //选着的图片
						var imageSrc = res.tempFilePaths[0] //将图片的地址赋值给imageSrc
						uni.uploadFile({
							url: 'http://134.175.182.248/prod-api/common/upload', // 服务器接口地址
							filePath: imageSrc, // 本地图片路径
							name: 'file', // 必须与后端 @RequestParam("file") 参数名一致！
							header: {
								'Authorization': 'Bearer ' + getToken()
							},
							success: (res) => {
								// 注意：uni.uploadFile 的 res.data 是字符串，可能需要 JSON.parse
								const data = JSON.parse(res.data || '{}');
								console.log('上传成功:', data);
								uni.showToast({
									title: '上传成功',
									icon: 'success',
									duration: 1000
								});

								// 存储图片路径（根据需求选择存储本地路径或服务器返回的URL）
								uni.setStorageSync('image1', data.url || imageSrc); // 假设服务器返回 {url: "..."}
								this.imageSrc =  "http://134.175.182.248/prod-api" + data.fileName  ; // 更新页面显示
								console.log(this.imageSrc);
							},
							fail: (err) => {
								console.error('上传失败:', err);
								uni.showModal({
									content: '上传失败: ' + (err.errMsg || '未知错误'),
									showCancel: false
								});
							}
						});
					},
					fail: (err) => { //图片接口调用失败的回调函数	
						console.log('chooseImage fail', err)
						// 判断是否允许调用摄像头
						uni.getSetting({
							success: (res) => {
								let authStatus = res.authSetting['scope.album'];
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
					}
				})
			},

			async submitFeedback() {
				if (!this.canSubmit) return
				this.isSubmitting = true
				uni.showLoading({
					title: '提交中...'
				})
				try {
					// API请求
					const feedbackData = {
						feedbackType: this.currentType,
						content: this.feedbackContent,
						image: this.imageSrc, // 实际项目中这里应该是服务器返回的图片URL
						contact: this.contactInfo,
					}
					// 2. 提交反馈数据给后端
					addUserFeedBack(feedbackData).then(res => {
						uni.showLoading({
							title: '提交中...'
						})
					})
					// 模拟API延迟
					await new Promise(resolve => setTimeout(resolve, 1000))
					uni.hideLoading()
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
					// 重置表单
					this.resetForm()
				} catch (error) {
					console.error('提交失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					})
				} finally {
					this.isSubmitting = false
				}
			},

			resetForm() {
				this.currentType = ''
				this.feedbackContent = ''
				this.imageSrc = ''
				this.contactInfo = ''
			}
		}
	}
</script>

<style lang="scss" scoped>
	.feedback-container {
		padding: 20rpx 30rpx;
		background-color: #fff;
		min-height: 100vh;
	}

	.feedback-header {
		padding: 20rpx 0;
		text-align: center;

		.header-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.feedback-section {
		margin-bottom: 40rpx;

		.section-title {
			display: block;
			font-size: 28rpx;
			color: #666;
			margin-bottom: 20rpx;
		}
	}

	.type-radio-group {
		display: flex;
		justify-content: space-around;

		.radio-label {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #333;
		}
	}

	.content-textarea {
		width: 100%;
		min-height: 200rpx;
		padding: 20rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		font-size: 28rpx;
		background-color: #f9f9f9;
	}

	.text-count {
		display: block;
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.upload-container {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
	}

	.demo {
		width: 250rpx;
		height: 250rpx;
		background: #FFF;
		padding: 10rpx;


		.uni-hello-addfile {
			width: 250rpx;
			height: 250rpx;
			text-align: center;
			font-size: 12px;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: rgba(202, 202, 202, 0.5);
		}

		.uni-hello-addfile:active {
			background-color: rgba(174, 247, 253, 0.5);
			border-bottom-left-radius: 8rpx;
		}
	}

	.upload-btn {
		width: 200rpx;
		height: 200rpx;
		border: 1rpx dashed #ccc;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #999;
		font-size: 24rpx;
		background-color: #f9f9f9;

		.upload-text {
			margin-top: 10rpx;
		}
	}

	.upload-tip {
		display: block;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.contact-input {
		width: 100%;
		height: 80rpx;
		padding: 0 20rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		font-size: 28rpx;
		background-color: #f9f9f9;
	}

	.submit-btn {
		margin-top: 60rpx;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		font-size: 32rpx;
		background-color: #007AFF;

		&[disabled] {
			background-color: #ccc;
			color: #fff;
		}
	}
</style>